// 全局变量
let currentChartType = 'bar';
let animationEnabled = true;
let showLegend = true;
let animationFrameId = null;

// DOM元素
const canvas = document.getElementById('chartCanvas');
const ctx = canvas.getContext('2d');
const chartTypeBtns = document.querySelectorAll('.chart-type-btn');
const addDataSetBtn = document.getElementById('addDataSet');
const dataSetsContainer = document.querySelector('.data-sets');
const chartTitleInput = document.getElementById('chartTitle');
const showLegendCheckbox = document.getElementById('showLegend');
const animationCheckbox = document.getElementById('animation');

// 初始化
function init() {
    // 设置Canvas的实际尺寸
    resizeCanvas();
    window.addEventListener('resize', resizeCanvas);
    
    // 添加事件监听
    setupEventListeners();
    
    // 绘制初始图表
    drawChart();
}

// 调整Canvas尺寸
function resizeCanvas() {
    const container = canvas.parentElement;
    const width = container.clientWidth;
    // 保持4:3的宽高比
    const height = width * 0.625;
    
    // 设置Canvas的显示尺寸
    canvas.style.width = `${width}px`;
    canvas.style.height = `${height}px`;
    
    // 设置Canvas的实际尺寸（考虑设备像素比）
    const dpr = window.devicePixelRatio || 1;
    canvas.width = width * dpr;
    canvas.height = height * dpr;
    
    // 缩放上下文
    ctx.scale(dpr, dpr);
    
    // 重绘图表
    drawChart();
}

// 设置事件监听
function setupEventListeners() {
    // 图表类型按钮
    chartTypeBtns.forEach(btn => {
        btn.addEventListener('click', () => {
            chartTypeBtns.forEach(b => b.classList.remove('active'));
            btn.classList.add('active');
            currentChartType = btn.dataset.type;
            drawChart();
        });
    });
    
    // 添加数据项按钮
    addDataSetBtn.addEventListener('click', addNewDataSet);
    
    // 数据输入变化监听
    dataSetsContainer.addEventListener('input', drawChart);
    
    // 图表选项
    chartTitleInput.addEventListener('input', drawChart);
    showLegendCheckbox.addEventListener('change', () => {
        showLegend = showLegendCheckbox.checked;
        drawChart();
    });
    animationCheckbox.addEventListener('change', () => {
        animationEnabled = animationCheckbox.checked;
        drawChart();
    });
}

// 添加新的数据项
function addNewDataSet() {
    const randomColor = getRandomColor();
    const newDataSet = document.createElement('div');
    newDataSet.className = 'data-set';
    newDataSet.innerHTML = `
        <label>标签：</label>
        <input type="text" class="label-input" placeholder="输入标签">
        <label>值：</label>
        <input type="number" class="value-input" placeholder="输入数值" min="0" value="0">
        <label>颜色：</label>
        <input type="color" class="color-input" value="${randomColor}">
    `;
    
    // 添加删除按钮
    const deleteBtn = document.createElement('button');
    deleteBtn.textContent = '🗑️ 删除';
    deleteBtn.className = 'delete-btn';
    deleteBtn.style.gridColumn = '1 / -1';
    deleteBtn.style.padding = '8px';
    deleteBtn.style.backgroundColor = '#e74c3c';
    deleteBtn.style.color = 'white';
    deleteBtn.style.border = 'none';
    deleteBtn.style.borderRadius = '4px';
    deleteBtn.style.cursor = 'pointer';
    deleteBtn.style.fontSize = '0.9rem';
    deleteBtn.addEventListener('click', () => {
        newDataSet.remove();
        drawChart();
    });
    
    newDataSet.appendChild(deleteBtn);
    dataSetsContainer.appendChild(newDataSet);
    
    // 为新添加的输入框添加事件监听
    const inputs = newDataSet.querySelectorAll('input');
    inputs.forEach(input => {
        input.addEventListener('input', drawChart);
    });
    
    // 重绘图表
    drawChart();
}

// 获取随机颜色
function getRandomColor() {
    const letters = '0123456789ABCDEF';
    let color = '#';
    for (let i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}

// 获取数据
function getData() {
    const dataSets = document.querySelectorAll('.data-set');
    const data = [];
    
    dataSets.forEach(set => {
        const label = set.querySelector('.label-input').value || '未命名';
        const value = parseFloat(set.querySelector('.value-input').value) || 0;
        const color = set.querySelector('.color-input').value;
        
        data.push({ label, value, color });
    });
    
    return data;
}

// 绘制图表
function drawChart() {
    // 清除画布
    ctx.clearRect(0, 0, canvas.clientWidth, canvas.clientHeight);
    
    const data = getData();
    const title = chartTitleInput.value || '数据图表';
    
    // 根据当前选择的图表类型绘制
    switch (currentChartType) {
        case 'bar':
            drawBarChart(data, title);
            break;
        case 'line':
            drawLineChart(data, title);
            break;
        case 'pie':
            drawPieChart(data, title);
            break;
    }
    
    // 绘制图例（饼图不需要外部图例，因为颜色直接在饼图上）
    if (showLegend && currentChartType !== 'pie') {
        drawLegend(data);
    }
}

// 绘制柱状图
function drawBarChart(data, title) {
    const width = canvas.clientWidth;
    const height = canvas.clientHeight;
    const padding = 40;
    const chartAreaWidth = width - padding * 2;
    const chartAreaHeight = height - padding * 3; // 额外留出标题和坐标轴标签的空间
    
    // 绘制标题
    drawTitle(title);
    
    // 如果没有数据，绘制提示信息
    if (data.length === 0 || data.every(item => item.value === 0)) {
        drawNoDataMessage();
        return;
    }
    
    // 找出最大值
    const maxValue = Math.max(...data.map(item => item.value)) || 1;
    
    // 绘制坐标轴
    drawAxes(padding, padding + chartAreaHeight, chartAreaWidth, chartAreaHeight);
    
    // 计算每个柱子的宽度和间距
    const totalBarsWidth = chartAreaWidth * 0.8; // 留出一些边距
    const barWidth = totalBarsWidth / data.length;
    const barSpacing = barWidth * 0.3;
    const barActualWidth = barWidth - barSpacing;
    
    // 绘制网格线和刻度
    drawGridLines(padding, padding + chartAreaHeight, chartAreaWidth, chartAreaHeight, maxValue);
    
    // 绘制柱子
    data.forEach((item, index) => {
        // 计算柱子高度（考虑动画）
        const targetHeight = (item.value / maxValue) * chartAreaHeight;
        const barX = padding + (index * barWidth) + barSpacing / 2;
        const barY = padding + chartAreaHeight - targetHeight;
        
        if (animationEnabled) {
            animateBar(barX, padding + chartAreaHeight, barActualWidth, 0, targetHeight, item.color, index);
        } else {
            // 直接绘制柱子
            ctx.fillStyle = item.color;
            ctx.fillRect(barX, barY, barActualWidth, targetHeight);
            
            // 添加边框
            ctx.strokeStyle = '#333';
            ctx.lineWidth = 1;
            ctx.strokeRect(barX, barY, barActualWidth, targetHeight);
            
            // 添加数值标签
            drawValueLabel(barX + barActualWidth / 2, barY - 10, item.value);
            
            // 添加X轴标签
            drawXAxisLabel(barX + barActualWidth / 2, height - padding, item.label);
        }
    });
}

// 绘制折线图
function drawLineChart(data, title) {
    const width = canvas.clientWidth;
    const height = canvas.clientHeight;
    const padding = 40;
    const chartAreaWidth = width - padding * 2;
    const chartAreaHeight = height - padding * 3;
    
    // 绘制标题
    drawTitle(title);
    
    // 如果没有数据，绘制提示信息
    if (data.length === 0 || data.every(item => item.value === 0)) {
        drawNoDataMessage();
        return;
    }
    
    // 找出最大值
    const maxValue = Math.max(...data.map(item => item.value)) || 1;
    
    // 绘制坐标轴和网格线
    drawAxes(padding, padding + chartAreaHeight, chartAreaWidth, chartAreaHeight);
    drawGridLines(padding, padding + chartAreaHeight, chartAreaWidth, chartAreaHeight, maxValue);
    
    // 计算点之间的间距
    const pointSpacing = chartAreaWidth / (data.length - 1);
    
    // 绘制线条和数据点
    ctx.beginPath();
    
    data.forEach((item, index) => {
        const x = padding + (index * pointSpacing);
        const y = padding + chartAreaHeight - (item.value / maxValue) * chartAreaHeight;
        
        if (index === 0) {
            ctx.moveTo(x, y);
        } else {
            ctx.lineTo(x, y);
        }
        
        // 绘制数据点
        drawDataPoint(x, y, item.color);
        
        // 添加数值标签
        drawValueLabel(x, y - 15, item.value);
        
        // 添加X轴标签
        drawXAxisLabel(x, height - padding, item.label);
    });
    
    ctx.strokeStyle = '#34495e';
    ctx.lineWidth = 2;
    ctx.stroke();
    
    // 添加区域填充（可选）
    if (data.length > 0) {
        ctx.lineTo(padding + chartAreaWidth, padding + chartAreaHeight);
        ctx.lineTo(padding, padding + chartAreaHeight);
        ctx.closePath();
        ctx.fillStyle = 'rgba(52, 152, 219, 0.1)';
        ctx.fill();
    }
}

// 绘制饼图
function drawPieChart(data, title) {
    const width = canvas.clientWidth;
    const height = canvas.clientHeight;
    const centerX = width / 2;
    const centerY = height / 2 + 10; // 稍微下移，为标题留出空间
    
    // 绘制标题
    drawTitle(title);
    
    // 如果没有数据，绘制提示信息
    if (data.length === 0 || data.every(item => item.value === 0)) {
        drawNoDataMessage();
        return;
    }
    
    // 计算总值
    const totalValue = data.reduce((sum, item) => sum + item.value, 0);
    
    // 计算饼图半径
    const radius = Math.min(width, height - 100) / 2.5;
    
    let currentAngle = -Math.PI / 2; // 从顶部开始
    
    // 绘制饼图扇区
    data.forEach((item, index) => {
        const sliceAngle = (item.value / totalValue) * 2 * Math.PI;
        const nextAngle = currentAngle + sliceAngle;
        
        if (animationEnabled) {
            animatePieSlice(centerX, centerY, radius, currentAngle, nextAngle, item.color, index);
        } else {
            // 绘制扇区
            ctx.beginPath();
            ctx.moveTo(centerX, centerY);
            ctx.arc(centerX, centerY, radius, currentAngle, nextAngle);
            ctx.closePath();
            ctx.fillStyle = item.color;
            ctx.fill();
            
            // 添加边框
            ctx.strokeStyle = '#fff';
            ctx.lineWidth = 2;
            ctx.stroke();
            
            // 计算扇区中心角度，用于绘制标签
            const labelAngle = currentAngle + sliceAngle / 2;
            const labelRadius = radius * 0.7; // 标签位置在扇区内部
            const labelX = centerX + Math.cos(labelAngle) * labelRadius;
            const labelY = centerY + Math.sin(labelAngle) * labelRadius;
            
            // 绘制标签（值和百分比）
            const percentage = Math.round((item.value / totalValue) * 100);
            ctx.fillStyle = '#fff';
            ctx.font = 'bold 14px Arial';
            ctx.textAlign = 'center';
            ctx.textBaseline = 'middle';
            ctx.fillText(`${percentage}%`, labelX, labelY);
        }
        
        // 绘制内部图例
        drawPieLegendItem(width - 120, 100 + index * 30, item, percentage);
        
        currentAngle = nextAngle;
    });
}

// 绘制标题
function drawTitle(title) {
    ctx.fillStyle = '#2c3e50';
    ctx.font = 'bold 20px Arial';
    ctx.textAlign = 'center';
    ctx.fillText(title, canvas.clientWidth / 2, 30);
}

// 绘制坐标轴
function drawAxes(x, y, width, height) {
    // X轴
    ctx.beginPath();
    ctx.moveTo(x, y);
    ctx.lineTo(x + width, y);
    ctx.strokeStyle = '#333';
    ctx.lineWidth = 2;
    ctx.stroke();
    
    // Y轴
    ctx.beginPath();
    ctx.moveTo(x, y);
    ctx.lineTo(x, y - height);
    ctx.stroke();
    
    // X轴箭头
    ctx.beginPath();
    ctx.moveTo(x + width, y);
    ctx.lineTo(x + width - 10, y - 5);
    ctx.lineTo(x + width - 10, y + 5);
    ctx.closePath();
    ctx.fillStyle = '#333';
    ctx.fill();
    
    // Y轴箭头
    ctx.beginPath();
    ctx.moveTo(x, y - height);
    ctx.lineTo(x - 5, y - height + 10);
    ctx.lineTo(x + 5, y - height + 10);
    ctx.closePath();
    ctx.fill();
    
    // 轴标签
    ctx.fillStyle = '#333';
    ctx.font = '14px Arial';
    ctx.textAlign = 'center';
    ctx.fillText('数据标签', x + width / 2, y + 30);
    
    ctx.save();
    ctx.translate(x - 30, y - height / 2);
    ctx.rotate(-Math.PI / 2);
    ctx.textAlign = 'center';
    ctx.fillText('数值', 0, 0);
    ctx.restore();
}

// 绘制网格线
function drawGridLines(x, y, width, height, maxValue) {
    ctx.strokeStyle = '#e0e0e0';
    ctx.lineWidth = 1;
    ctx.setLineDash([5, 5]);
    
    // 水平网格线
    const gridLines = 5;
    for (let i = 0; i <= gridLines; i++) {
        const gridY = y - (height / gridLines) * i;
        const value = (maxValue / gridLines) * i;
        
        ctx.beginPath();
        ctx.moveTo(x, gridY);
        ctx.lineTo(x + width, gridY);
        ctx.stroke();
        
        // Y轴刻度标签
        ctx.fillStyle = '#666';
        ctx.font = '12px Arial';
        ctx.textAlign = 'right';
        ctx.fillText(value.toFixed(0), x - 10, gridY + 4);
    }
    
    ctx.setLineDash([]);
}

// 绘制数据点
function drawDataPoint(x, y, color) {
    ctx.beginPath();
    ctx.arc(x, y, 6, 0, Math.PI * 2);
    ctx.fillStyle = color;
    ctx.fill();
    ctx.strokeStyle = '#fff';
    ctx.lineWidth = 2;
    ctx.stroke();
}

// 绘制数值标签
function drawValueLabel(x, y, value) {
    ctx.fillStyle = '#333';
    ctx.font = '12px Arial';
    ctx.textAlign = 'center';
    ctx.fillText(value.toFixed(0), x, y);
}

// 绘制X轴标签
function drawXAxisLabel(x, y, label) {
    ctx.fillStyle = '#333';
    ctx.font = '12px Arial';
    ctx.textAlign = 'center';
    ctx.fillText(label, x, y + 20);
}

// 绘制图例
function drawLegend(data) {
    const legendX = canvas.clientWidth - 150;
    const legendY = 60;
    const legendItemHeight = 25;
    
    ctx.fillStyle = '#2c3e50';
    ctx.font = '14px Arial';
    ctx.textAlign = 'left';
    ctx.fillText('图例：', legendX, legendY - 5);
    
    data.forEach((item, index) => {
        const itemY = legendY + index * legendItemHeight;
        
        // 绘制颜色块
        ctx.fillStyle = item.color;
        ctx.fillRect(legendX, itemY, 15, 15);
        
        // 绘制边框
        ctx.strokeStyle = '#333';
        ctx.lineWidth = 1;
        ctx.strokeRect(legendX, itemY, 15, 15);
        
        // 绘制标签
        ctx.fillStyle = '#333';
        ctx.font = '12px Arial';
        ctx.fillText(`${item.label} (${item.value})`, legendX + 25, itemY + 12);
    });
}

// 绘制饼图图例项
function drawPieLegendItem(x, y, item, percentage) {
    // 绘制颜色块
    ctx.fillStyle = item.color;
    ctx.fillRect(x, y, 15, 15);
    
    // 绘制边框
    ctx.strokeStyle = '#333';
    ctx.lineWidth = 1;
    ctx.strokeRect(x, y, 15, 15);
    
    // 绘制标签
    ctx.fillStyle = '#333';
    ctx.font = '12px Arial';
    ctx.textAlign = 'left';
    ctx.fillText(`${item.label} ${percentage}%`, x + 25, y + 12);
}

// 绘制无数据提示
function drawNoDataMessage() {
    ctx.fillStyle = '#95a5a6';
    ctx.font = '16px Arial';
    ctx.textAlign = 'center';
    ctx.fillText('暂无数据', canvas.clientWidth / 2, canvas.clientHeight / 2);
}

// 动画函数
function animateBar(x, y, width, startHeight, targetHeight, color, index) {
    // 清除之前的动画
    if (animationFrameId) {
        cancelAnimationFrame(animationFrameId);
    }
    
    let currentHeight = startHeight;
    const duration = 500; // 动画持续时间（毫秒）
    const startTime = performance.now();
    
    function animate(currentTime) {
        const elapsed = currentTime - startTime;
        const progress = Math.min(elapsed / duration, 1);
        
        // 使用缓动函数
        const easeOutProgress = 1 - Math.pow(1 - progress, 3);
        
        currentHeight = startHeight + (targetHeight - startHeight) * easeOutProgress;
        
        // 清除当前柱子区域
        ctx.clearRect(x - 5, y - targetHeight - 20, width + 10, targetHeight + 30);
        
        // 绘制柱子
        ctx.fillStyle = color;
        ctx.fillRect(x, y - currentHeight, width, currentHeight);
        
        // 添加边框
        ctx.strokeStyle = '#333';
        ctx.lineWidth = 1;
        ctx.strokeRect(x, y - currentHeight, width, currentHeight);
        
        // 添加数值标签
        const currentValue = (currentHeight / targetHeight) * parseFloat(document.querySelectorAll('.value-input')[index].value);
        drawValueLabel(x + width / 2, y - currentHeight - 10, currentValue);
        
        if (progress < 1) {
            animationFrameId = requestAnimationFrame(animate);
        }
    }
    
    animationFrameId = requestAnimationFrame(animate);
}

// 饼图动画
function animatePieSlice(cx, cy, radius, startAngle, endAngle, color, index) {
    let currentAngle = startAngle;
    const duration = 500;
    const startTime = performance.now();
    const angleDiff = endAngle - startAngle;
    
    function animate(currentTime) {
        const elapsed = currentTime - startTime;
        const progress = Math.min(elapsed / duration, 1);
        
        // 使用缓动函数
        const easeOutProgress = 1 - Math.pow(1 - progress, 3);
        
        currentAngle = startAngle + angleDiff * easeOutProgress;
        
        // 清除整个饼图区域
        ctx.clearRect(cx - radius - 10, cy - radius - 10, (radius + 10) * 2, (radius + 10) * 2);
        
        // 重新绘制所有已经动画完成的扇区
        const data = getData();
        const totalValue = data.reduce((sum, item) => sum + item.value, 0);
        let prevAngle = -Math.PI / 2;
        
        data.forEach((item, i) => {
            const sliceAngle = (item.value / totalValue) * 2 * Math.PI;
            const sliceEndAngle = i <= index ? (i < index ? prevAngle + sliceAngle : currentAngle) : prevAngle;
            
            ctx.beginPath();
            ctx.moveTo(cx, cy);
            ctx.arc(cx, cy, radius, prevAngle, sliceEndAngle);
            ctx.closePath();
            ctx.fillStyle = item.color;
            ctx.fill();
            
            // 添加边框
            ctx.strokeStyle = '#fff';
            ctx.lineWidth = 2;
            ctx.stroke();
            
            prevAngle += sliceAngle;
        });
        
        if (progress < 1) {
            requestAnimationFrame(animate);
        } else {
            // 动画完成后，绘制饼图标签
            const percentage = Math.round((data[index].value / totalValue) * 100);
            const labelAngle = startAngle + angleDiff / 2;
            const labelRadius = radius * 0.7;
            const labelX = cx + Math.cos(labelAngle) * labelRadius;
            const labelY = cy + Math.sin(labelAngle) * labelRadius;
            
            ctx.fillStyle = '#fff';
            ctx.font = 'bold 14px Arial';
            ctx.textAlign = 'center';
            ctx.textBaseline = 'middle';
            ctx.fillText(`${percentage}%`, labelX, labelY);
        }
    }
    
    requestAnimationFrame(animate);
}

// 页面加载完成后初始化
window.addEventListener('DOMContentLoaded', init);